import axios from "axios";
import store from "../../store"
import { v4 as uuidv4 } from "uuid";
var COS = require("cos-js-sdk-v5");

const cos = new COS({
    getAuthorization: function(options, callback) {
        // 异步获取临时密钥
        axios.get("/api/file/sts").then((response) => {
            var data = response.data.data;
            var credentials = data.credentials;
            if (!data || !credentials) {
                console.log(data);
                console.log(credentials);
                return console.error("credentials invalid");
            }
            callback({
                TmpSecretId: credentials.tmpSecretId,
                TmpSecretKey: credentials.tmpSecretKey,
                SecurityToken: credentials.sessionToken,
                // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
                ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
            });
        });
    },
});


const bucket = "heaven-1305422781";
const region = "ap-chengdu";
const fileService = {
    uploadFile: function(file, callback, onProgressUpdate) {
        var result = {
            success: false,
            exc: "",
            url: null,
        }
        let extensionName = file.name.split(".").pop();
        var fileKey = uuidv4() + "." + extensionName;

        cos.uploadFile({
                Bucket: bucket /* 必须 */ ,
                Region: region /* 存储桶所在地域，必须字段 */ ,
                Key: fileKey /* 必须 */ ,
                Body: file /* 必须 */ ,
                SliceSize: 1024 *
                    1024 *
                    5 /* 触发分块上传的阈值，超过5MB使用分块上传，非必须 */ ,
                onTaskReady: function(taskId) {
                    /* 非必须 */
                    console.log(taskId);
                    store.commit("resource/uploadStart");
                },
                onProgress: function(progressData) {
                    /* 非必须 */
                    console.log(JSON.stringify(progressData));
                    store.commit("resource/uploadUpdate", progressData)
                    if (onProgressUpdate != undefined && onProgressUpdate != null && (typeof(() => {})) === (typeof onProgressUpdate)) {
                        onProgressUpdate(progressData);
                    }
                },
                onFileFinish: function(err, data, options) {
                    console.log(options.Key + "上传" + (err ? "失败" : "完成"));
                    if (!err) {
                        result.success = true;
                        result.url = "http://" + data.Location
                        store.commit("resource/uploadEnd", result)
                        callback(result);
                    }
                },
            },
            function(err) {
                if (err != null) {
                    result.exc = err;
                    console.log(result);
                    store.commit("resource/uploadEnd", result)
                    callback(result);
                }
            }
        );

    }
}
export default fileService;